import { View, RichText } from '@tarojs/components';
import {Flex, Image, Circle, ActionSheet, Loading} from '@taroify/core';
import {BookmarkOutlined, OrdersOutlined} from '@taroify/icons';
import { ChatMessage, MessageContent } from "@/types/conservationType";
import { AgentRes } from "@/types/agentType";
import { useDispatchTextBlock } from "@/hooks/textBlock";
import {marked} from 'marked';
import Taro from "@tarojs/taro";
import {useState} from "react";
import {mdToDocxAPI, mdToPDFAPI} from "@/api/util"; // 引入 marked

export default function ChatContainer(props: { agent: AgentRes, chat_messages: ChatMessage[], note_collection_uuid: string, generating: boolean }) {
  // ? Props
  const { agent, chat_messages, note_collection_uuid, generating } = props;
  const dispatchTextBlock = useDispatchTextBlock();

  // 处理笔记设置
  const handleNoteSet = async (message: MessageContent[]) => {
    let note = '';
    message.forEach((item) => {
      if (item.type === 'text') {
        note += item.content;
      }
    });
    await dispatchTextBlock.addTextBlock({ content: note, collection_uuid: note_collection_uuid });
    await Taro.showToast({title: '笔记添加成功！', icon: 'none'});
  };

  // 将 Markdown 解析为 HTML
  const renderMarkdown = (content: string) => {
    return marked(content); // 使用 marked 解析 Markdown
  };

  // 新增图片预览处理函数
  const handlePreviewImage = (contents: MessageContent[], clickedIndex: number) => {
    // 过滤出所有图片内容
    const images = contents.filter(item => item.type === 'image');
    // 获取点击的图片内容
    const clickedContent = contents[clickedIndex];

    // 类型安全校验
    if (clickedContent.type !== 'image') return;

    // 生成图片 URL 数组
    const urls = images.map(img => img.content);
    // 查找当前图片索引
    const currentIndex = images.findIndex(img => img.content === clickedContent.content);

    if (currentIndex !== -1) {
      Taro.previewImage({
        current: urls[currentIndex],  // 当前显示图片
        urls: urls                    // 所有可预览图片
      });
    }
  };

  const [chatContentActionVisible, setChatContentActionVisible] = useState(false);
  const [selectChatContent, setSelectContent] = useState('');

  const handleChatContentAction = (message: MessageContent[]) => {
    let note = '';
    message.forEach((item) => {
      if (item.type === 'text') {
        note += item.content;
      }
    });
    setSelectContent(note);
    setChatContentActionVisible(true);
  };

  const handleChatContentSheetClick = async (event: { value: string; }) => {
    if (!selectChatContent) return;

    try {
      let fileUrl: string;

      if (event.value === 'word') {
        const res = await mdToDocxAPI(selectChatContent);
        fileUrl = res.url;
      } else if (event.value === 'pdf') {
        const res = await mdToPDFAPI(selectChatContent);
        fileUrl = res.url;
      } else {
        return;
      }

      // 下载文件到临时路径
      const { tempFilePath } = await Taro.downloadFile({
        url: fileUrl
      });

      await Taro.saveFile({
        tempFilePath: tempFilePath,
        success: async (result) => {
          // 打开文档预览
          await Taro.openDocument({
            filePath: result.savedFilePath,
            showMenu: true // 显示右上角菜单（可用于转发、保存等）
          });
        },
        fail: (error) => {
          console.error('保存文件失败:', error);
          Taro.showToast({
            title: '文件保存失败',
            icon: 'none'
          });
        }
      });

    } catch (error) {
      console.error('下载失败:', error);
      await Taro.showToast({
        title: '文件下载失败',
        icon: 'none'
      });
    }

    setChatContentActionVisible(false);
  };


  return (
    <View style={{ height: '100%', width: '100%'}}>
      {/* 头像 */}
      <View style={{ padding: '20rpx 0 20px 0', display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
        <Image
          src={`${process.env.TARO_APP_BASE_URL}${agent.cover_image}`}
          style={{ width: '300rpx', height: '300rpx', objectFit: 'cover', borderRadius: '50%' }}
        />
      </View>

      {/* 聊天记录 */}
      <View style={{display: 'flex', padding: '20rpx', flexDirection: 'column', alignItems: 'center'}}>
        {/* 系统消息 */}
        <View key={-1} style={{ width: '100%', padding: '10rpx 0 10rpx 0'}}>
          <View style={{ width: '100%', display: 'flex', justifyContent: 'flex-start' }}>
            <View
              style={{
                display: 'flex',
                justifyContent: 'flex-start',
                backgroundColor: '#dfdfdf',
                maxWidth: '100%',
                fontSize: '45rpx',
                padding: '20rpx',
                borderRadius: '30rpx',
                wordWrap: 'break-word',
              }}
            >
              <RichText nodes={renderMarkdown(agent.welcome_info)} style={{fontSize: '30rpx !important', userSelect: 'text'}} /> {/* 使用 RichText 渲染 Markdown */}
            </View>
          </View>
        </View>

        {/* 用户和其他角色的消息 */}
        {chat_messages.map((message, index) => (
          <View key={index} style={{ width: '100%', padding: '10rpx 0 20rpx 0'}}>
            <View style={{ width: '100%', display: 'flex', justifyContent: message.role === 'system' ? 'flex-start' : 'flex-end' }}>
              <View
                style={{
                  maxWidth: '100%',
                  display: 'flex',
                  flexDirection: 'column',
                  justifyContent: message.role === 'system' ? 'flex-start' : 'flex-end',
                  backgroundColor: message.role === 'system' ? '#dfdfdf' : '#8596dc',
                  fontSize: '45rpx',
                  padding: '20rpx',
                  borderRadius: '30rpx',
                  overflowX: "auto",
                  wordWrap: 'break-word',
                }}
              >
                {/* 判断消息类型 */}
                {message.contents.map((content, contentIndex) => {
                  switch (content.type) {
                    case 'text':
                      return <RichText key={contentIndex} style={{fontSize: '30rpx !important', userSelect: 'text'}} nodes={renderMarkdown(content.content)} />; // 使用 RichText 渲染 Markdown
                    case 'image':
                      return <Image
                        key={contentIndex}
                        style={{ width: '100%', minWidth: '300rpx'}}
                        src={content.content}
                        onClick={() => handlePreviewImage(message.contents, contentIndex)} // 新增点击事件
                        mode='aspectFit'
                      />;
                    case 'progress':
                      return (
                        <Circle key={contentIndex} percent={parseInt(content.content)}>
                          {parseInt(content.content).toFixed(0)}%
                        </Circle>
                      );
                    default:
                      return null;
                  }
                })}
              </View>
            </View>
            {generating && index === chat_messages.length - 1 && <Loading style={{color: '#1989fa', marginTop: '15rpx'}} />}
            {message.role === 'system' && !generating && (
              <Flex style={{ paddingTop: '5px' }} gutter={20}>
                {/*<Flex.Item><Replay style={{ fontSize: '45rpx' }} /></Flex.Item>*/}
                {/*<Flex.Item><GoodJobOutlined style={{ fontSize: '45rpx' }} /></Flex.Item>*/}
                <Flex.Item><OrdersOutlined style={{ fontSize: '45rpx' }} onClick={() => handleChatContentAction(message.contents)} /></Flex.Item>
                <Flex.Item><BookmarkOutlined style={{ fontSize: '45rpx' }} onClick={() => handleNoteSet(message.contents)} /></Flex.Item>
              </Flex>
            )}
          </View>
        ))}
      </View>

      <ActionSheet
        style={{width: '100vw'}}
        cancelText='取消'
        description='导出为'
        open={chatContentActionVisible}
        onSelect={handleChatContentSheetClick}
        onCancel={() => setChatContentActionVisible(false)}
        onClose={() => setChatContentActionVisible(false)}
        actions={[
          { name: 'Word 文档', value: 'word', style:{ color: '#1890ff'} },
          { name: 'PDF 文件', value: 'pdf', style:{ color: '#ff4d4f'} },
        ]}
      />
    </View>
  );
}
